package com.jzy.common.config.Exception;

import java.util.Collections;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;

import com.jzy.common.utils.AjaxResult;

/**
 * 
 * 类描述： 处理异常，返回对应json或html
 * 创建者： jiaozy
 * 项目名称： ssm
 * 创建时间： 2019年3月7日 上午10:24:08
 * Email：jzy19890914@gmail.com
 */
public class MyErrorController extends BasicErrorController {

	public MyErrorController(ErrorAttributes errorAttributes,
			ErrorProperties errorProperties) {
		super(errorAttributes, errorProperties);
	}

	/*
	public MyErrorController(ServerProperties serverProperties) { 
		super(new DefaultErrorAttributes(), serverProperties.getError()); 
	}*/
	
	/**
	 * 覆盖默认的HTML响应
	 */
	@Override
	public ModelAndView errorHtml(HttpServletRequest request,
			HttpServletResponse response) {
		
		HttpStatus status = getStatus(request);
		response.setStatus(status.value());
		Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
				request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
		
		ModelAndView modelAndView = resolveErrorView(request, response, status, model);
		return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
	}

	/**
	 * 覆盖默认的Json响应
	 */
	@Override
	public ResponseEntity<Map<String, Object>> error(
			HttpServletRequest request) {
		
		Map<String, Object> body = getErrorAttributes(request,
				isIncludeStackTrace(request, MediaType.ALL));
		
		HttpStatus status = getStatus(request);
		AjaxResult ar=AjaxResult.failure((String)body.get("message"));
		return new ResponseEntity<>(body, status);
	}

	
}
